package com.example.campusforumapi.controller;

import com.example.campusforumapi.entity.Category;
import com.example.campusforumapi.entity.Department;
import com.example.campusforumapi.service.CategoryService;
import com.example.campusforumapi.service.DepartmentService;
import com.example.campusforumapi.util.PageResult;
import com.example.campusforumapi.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/articlecategories")
public class CategoryController extends BaseController{
    @Autowired
    private CategoryService categoryService;
    /*
     * 按条件  分页查询
     * */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result list(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer pageSize
    ){
        //查询并封装分页结果集
        PageResult categoryPage = categoryService.getCagegoryPage(page,pageSize);
        return Result.success(categoryPage);
    }

    //    删除一条记录
    @DeleteMapping("/delete/{ids}")
    public Result delete(@PathVariable List<Integer> ids){
        categoryService.delCategory(ids);
        return Result.success();
    }

    //    新增一条记录
    @PostMapping ("/insert")
    public Result insert(@RequestBody Category category){
        if(StringUtils.isEmpty(category.getCategoryId()) || StringUtils.isEmpty(category.getCategoryName())){
            return Result.error("分类名称名及分类id不能为空");
        }
        else if (categoryService.findsameCategoryName(category.getCategoryName())>=1) {
            return Result.error("文章分类名称已存在");
        }
        else if(categoryService.findsameCategoryId(category.getCategoryId())>=1){
            return Result.error("该文章分类ID已存在");
        }
        else if(categoryService.insertCategory(category) > 0){
            return Result.success("插入成功");
        }else{
            return Result.error("插入异常");
        }

    }

    //    修改一条记录
    @PutMapping("/update")
    public Result update(@RequestBody Category category){
        if(categoryService.updCategory(category) > 0){
            return Result.success("修改成功");
        }else{
            return Result.error("修改失败，该分类不存在");
        }

    }

}
